'use strict'

const { Product, Op } = require('../model');
// 博主的数据列表，可能存在关键字查找的情况
let fn_product_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list = await Product.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { title: isNaN(keyword) ? 0 : keyword },
                    { digest: isNaN(keyword) ? 0 : keyword },
                    { content: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { classify: keyword },
                    { author: keyword },
                    { time:keyword  }
                ]
            },
            order: ['id']
        })
        ctx.body = list;
    } else {
        let list = await Product.findAll({
            order: ['id']
        })
        ctx.body = list;

    }
}

//获取博客id
let fn_product_id = async (ctx, next) => {
    let id = ctx.request.params.id;
    let arr = await Product.findByPk(id);
    if (arr.lenght > 0) {
        ctx.body = {
            code: 1000,
            data: arr[0],
            msg: '获取成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '没有找到'
        }
    }
}

//删除记录

let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;
    let product = await Product.findByPk(id);
    if (product) {
        await product.destroy({
            where: {
                id: id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id: id },
            msg: '删除指定记录成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: '',
            msg: '指定的删除记录不存在，请重试'
        }
    }
}

let fn = (ctx,next)=>{
    ctx.body='这是一个页面'
}

module.exports = {
    'get /product': fn_product_list,
    'get /product/:id': fn_product_id,
    'delete /product/:id': fn_delete,
    'get /':fn,
}